package com.molichuxing.gateway.api.aspect;

import java.lang.reflect.Field;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.molichuxing.framework.annotation.FileUrl;
import com.molichuxing.framework.contants.RedisKeyConst;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.RedisUtil;

@Aspect
@Order(4)
@Component
public class GeneratePresignedUrlAspect {
	private final static Logger logger = LoggerFactory.getLogger("[]");

	@Resource
	private RedisUtil redisUtil;

	@Pointcut("execution(public * com.molichuxing.gateway.api.services.impl..*(..))")
	public void url() {
	}

	@SuppressWarnings({ "rawtypes" })
	@AfterReturning(returning = "returnValue", pointcut = "url()")
	public void doAfterReturning(JoinPoint joinPoint, Object returnValue) {
		String isGenerate = redisUtil.get(RedisKeyConst.FILE_GENERATE);

		try {
			if (returnValue instanceof ResponseResult && "true".equalsIgnoreCase(isGenerate)) {
				ResponseResult result = (ResponseResult) returnValue;
				Object data = result.getData();
				if (data == null) {
					return;
				}
				Class<?> clz = data.getClass();
				Field[] fields = clz.getDeclaredFields();
				if (fields == null) {
					return;
				}

				for (Field field : fields) {
					if (field.isAnnotationPresent(FileUrl.class)) {
						// 打开私有访问
						field.setAccessible(true);
						// 获取属性值
						Object value = field.get(returnValue);

						System.out.println(value);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}
